import 'package:account_book/common/constants/storage_key.dart';
import 'package:account_book/common/dao/book_dao.dart';
import 'package:account_book/common/entity/book.dart';
import 'package:account_book/common/services/storage_service.dart';
import 'package:account_book/common/utils/toast_util.dart';
import 'package:account_book/pages/my_book/index.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class MyBookController extends GetxController {

  final state = MyBookState();

  final inputController = TextEditingController();

  @override
  void onReady() {
    super.onReady();
    _loadMyBookData();
  }

  @override
  void onClose() {
    inputController.dispose();
    super.onClose();
  }

  /// 加载数据
  void _loadMyBookData () async {
    List<Book> list = await BookDao.instance.getAll();
    state.bookList.clear();
    if (list.isNotEmpty) {
      state.bookList.addAll(list);
    }
  }

  /// 保存
  Future<void> saveBook() async {
    final value = inputController.text;
    if (value.isEmpty) {
      ToastUtil.show("名称不能为空");
      return;
    }
    Book book = Book(name: value);
    book.createDate = DateUtil.formatDate(DateTime.now(), format: "yyyy-MM-dd HH:mm:ss");
    await BookDao.instance.insert(book.toMap());
    _loadMyBookData();
  }

  /// 更新
  Future<void> updateBook(Book accountBook) async {
    await BookDao.instance.update({"id": accountBook.id}, accountBook.toMap());
    _loadMyBookData();
  }

  /// 切换当前账本
  Future<void> switchBook(Book accountBook) async {
    await BookDao.instance.switchUseState(accountBook.id!);
    StorageService.instance.setInt(StorageKeyConstants.currentBook, accountBook.id!);
    ToastUtil.show("切换成功");
    _loadMyBookData();
  }
}